<template>
  <div class=''>

    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <!-- 添加角色 -->
      <el-row :gutter="20">
        <el-col :span='4'>
          <el-button type="primary" @click="addRoleDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 角色列表区域 -->
      <el-table :data="roleList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item1, i1) in scope.row.children" :key="item1.id"
              :class="['bdbottom',i1 === 0 ? 'bdtop' : '','vcenter']"
            >

              <!-- 渲染一级权限 -->
              <el-col :span='5'>
                <el-tag
                  closable @close="removeRightByid(scope.row,item1.id)"
                >{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>

              <!-- 渲染二级和三级权限 -->
              <el-col :span='19'>

                <!-- 通过for 循环 嵌套渲染二级权限 -->
                <el-row
                  v-for="(item2, i2) in item1.children" :key="item2.id"
                  :class="[i2 === 0? '' : 'bdtop','vcenter']"
                >
                  <el-col :span='6'>
                    <el-tag
                      type="success"
                      closable @close="removeRightByid(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span='18'>

                    <!-- 通过for 循环 嵌套渲染三级权限 -->
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children" :key="item3.id"
                      closable @close="removeRightByid(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>

        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">

            <!-- 修改角色按钮 -->
            <el-button
              type="primary" icon="el-icon-edit" size="mini"
              @click="showEditRoleDialog(scope.row.id)"
            >编辑</el-button>

            <!-- 删除角色按钮 -->
            <el-button
              type="danger" icon="el-icon-delete" size="mini"
              @click="removeRoleById(scope.row.id)"
            >删除</el-button>

            <!-- 分配角色按钮 -->
            <el-button
              type="warning" icon="el-icon-setting" size="mini"
              @click="showSetRightDialog(scope.row)"
            >分配角色</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限的对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightDialogClosed"
      >

      <!-- 内容主体区域 -->
      <el-tree
        :data="powerList"
        :props="powerTreeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defkeys"
        ref="treeRef"
      >
      </el-tree>

      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="addRoleDialogVisible"
      width="50%"
      @close="addRoleDialogClosed"
      >

      <!-- 内容主体区域 -->
      <el-form
      :model="addRoleFrom"
      :rules="addRoleFromRules"
      label-width="100px"
      ref="addRoleFromRef"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleFrom.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoleFrom.roleDesc"></el-input>
        </el-form-item>
      </el-form>

      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="editRoleDialogVisible"
      width="50%"
      @close="editRoleDialogClosed"
      >

      <!-- 内容主体区域 -->
      <el-form
      :model="editRoleFrom"
      :rules="editRoleFromRules"
      label-width="100px"
      ref="editRoleFromRef"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoleFrom.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRoleFrom.roleDesc"></el-input>
        </el-form-item>
      </el-form>

      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>

export default {
  name: 'Roles',
  props: {

  },
  data () {
    return {
      roleList: [],
      // 控制分配对话框的显示和隐藏
      setRightDialogVisible: false,
      // 所有权限列表
      powerList: [],
      powerTreeProps: {
        children: 'children',
        label: 'authName'
      },
      // 默认选中的节点id值数组
      defkeys: [],
      roleId: null,
      // 与添加角色相关信息
      addRoleDialogVisible: false,
      addRoleFrom: {
        roleName: '',
        roleDesc: ''
      },
      addRoleFromRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      // 与编辑角色相关信息
      editRoleDialogVisible: false,
      editRoleFrom: {},
      editById: '',
      editRoleFromRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    // 获取所有的用户列表
    this.getRoleList()
  },
  methods: {

    // 获取所有的用户列表
    async getRoleList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.roleList = res.data
    },

    // 根据id删除对应的权限
    async removeRightByid (role, rightId) {
      // 弹框提示用户是否删除
      const confirmResult = await this.$confirm('此操作将删除权限', '提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning'
      }).catch(err => {
        return err
      })
      if (confirmResult !== 'confirm') {
        return this.$message.info('您取消了操作')
      }
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) {
        return this.$message.error('权限删除失败')
      }
      // 提示权限删除成功
      this.$message.success('权限删除成功')
      // 更新当前用户的权限列表
      role.children = res.data
    },

    // 展示权限对话框
    async showSetRightDialog (role) {
      this.roleId = role.id
      // 获取所有权限列表
      const type = 'tree'
      const { data: res } = await this.$http.get('rights/' + type)
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败')
      }
      this.powerList = res.data

      // 递归获取三级节点的 id
      this.getLeafKeys(role, this.defkeys)

      // 显示分配对话框
      this.setRightDialogVisible = true
    },

    // 通过递归的形式，获取角色下所有的三级权限id
    getLeafKeys (node, arr) {
      // 若当前节点不包括children,则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },

    // 监听分配权限框的关闭事件
    setRightDialogClosed () {
      this.defkeys = []
    },

    // 为角色分配权限
    async allotRights () {
      // console.log(...this.$refs.treeRef.getHalfCheckedKeys())
      const keys = [
        ...this.$refs.treeRef.getHalfCheckedKeys(),
        ...this.$refs.treeRef.getCheckedKeys()
      ]
      const idStr = keys.join(',')

      // 发起权限分配请求
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, {
        rids: idStr
      })
      if (res.meta.status !== 200) {
        return this.$message.error('权限分配失败')
      }
      this.$message.success('权限分配成功')

      // 更新角色权限列表
      this.getRoleList()

      // 隐藏权限分配对话框
      this.setRightDialogVisible = false
    },

    // 添加角色
    addRole () {
      this.$refs.addRoleFromRef.validate(async valid => {
        if (!valid) return

        // 发起添加用户请求
        const { data: res } = await this.$http.post('roles', this.addRoleFrom)
        if (res.meta.status !== 201) return this.$message.error('角色添加失败')
        this.$message.success('角色添加成功')

        // 隐藏添加用户对话框
        this.addRoleDialogVisible = false

        // 重新获取用户列表
        this.getRoleList()
      })
    },

    // 当添加角色对话框关闭,清空数据
    addRoleDialogClosed () {
      this.$refs.addRoleFromRef.resetFields()
    },

    // 编辑角色对话框
    async showEditRoleDialog (id) {
      // 根据用户id,查询用户信息
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.editRoleFrom = res.data
      this.editRoleDialogVisible = true
    },

    // 编辑角色
    editRole () {
      this.$refs.editRoleFromRef.validate(async valid => {
        if (!valid) return

        // 发起编辑角色请求
        const { data: res } = await this.$http.put('roles/' + this.editRoleFrom.roleId, {
          roleName: this.editRoleFrom.roleName,
          roleDesc: this.editRoleFrom.roleDesc
        })
        if (res.meta.status !== 200) return this.$message.error('角色编辑失败')
        this.$message.success('角色编辑成功')

        // 隐藏编辑角色对话框
        this.addRoleDialogVisible = false

        // 重新获取用户列表
        this.getRoleList()
      })
    },

    // 当编辑角色对话框关闭,清空数据
    editRoleDialogClosed () {
      this.$refs.editRoleFromRef.resetFields()
    },

    // 删除角色
    async removeRoleById (id) {
      // 弹框提示用户是否删除
      const confirmResult = await this.$confirm('此操作将永久删除该角色', '提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning'
      }).catch(err => {
        return err
      })

      // 判断是否发起删除角色请求
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      // 发起删除角色请求
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除角色失败')
      }
      this.$message.success('角色删除成功')

      // 重新获取用户列表
      this.getRoleList()
    }
  }
}
</script>
<style scoped>
.el-breadcrumb{
  margin-bottom: 15px;
  font-size: 12px;
}
.box-card{
  box-shadow:  0 1px 1px rgba(0, 0, 0, 0.15) !important;
}
.el-table{
  margin-top: 15px;
}
.el-tag{
  margin: 7px;
}
.bdtop{
  border-top: 1px solid #eee;
}
.bdbottom{
  border-bottom: 1px solid #eee;
}
.vcenter{
  display: flex;
  align-items: center;
}
</style>
